<template>
  <div class="wrapper">
    <div
        style="margin: 200px auto; background-color: #fff; width: 350px; height: 300px; padding: 20px; border-radius: 10px">
      <div style="margin: 20px 0; text-align: center; font-size: 24px"><b>管 理 员 登 录</b></div>
      <el-form :model="admin" :rules="rules" ref="userForm">
        <el-form-item prop="staffName">
          <el-input size="medium" style="margin: 10px 0" prefix-icon="el-icon-user" v-model="admin.staffName"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="medium" style="margin: 10px 0" prefix-icon="el-icon-lock" show-password
                    v-model="admin.password"></el-input>
        </el-form-item>
        <el-form-item style="margin: 10px 0; text-align: right">
          <el-button type="warning" size="small" autocomplete="off" @click="$message.info('功能暂未开放')">注册</el-button>
          <el-button type="primary" size="small" autocomplete="off" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
export default {
  name: "Login",
  data() {
    return {
      admin: sessionStorage.getItem("admin") ? JSON.parse(sessionStorage.getItem("admin")) : {},
      rules: {
        staffName: [
          {required: true, message: '请输入管理员用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
      }
    }
  },
  created() {
    if (this.admin.staffId){
      this.$router.push("/home")
      this.$message.info('你已经登录了！')
    }
  },
  methods: {
    login() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {  // 表单校验合法
          request.post("/login",this.admin).then(res => {
            if (res.code === 200) {
              sessionStorage.setItem("admin", JSON.stringify(res.data))
              this.$message.success("登录成功")
              this.$router.push("/home")
            } else {
              this.$message.error("登录失败")
            }
          })
        }
      });
    }
  }
}
</script>

<style>
.wrapper {
  height: 100vh;
  background-image: url("../assets/loginBg.jpg");
  overflow: hidden;
  background-size: 100%;
}
</style>
